import { useState, useEffect, useContext } from "react";
import {
  Box,
  Text,
  Flex,
  IconButton,
  Collapse,
  useToast,
} from "@chakra-ui/react";
import { ChevronDownIcon, ChevronUpIcon } from "@chakra-ui/icons";
import newKeyInfos from "@/src/config/newKeyInfos.json"; // 确保路径正确
import { Keycode, KeyGroup } from "@/src/types/types.v1";
import { MainContext } from "@/src/providers/MainProvider";
import { useTranslation } from "@/src/i18n";

const KeyboardKey = () => {
  const {
    connectedMouse,
    mouseKeys,
    setMouseKeys,
    selKeyIndex,
    profile,
    profileIndex,
  } = useContext(MainContext);

  const toast = useToast();
  const [nowIndex, setNowIndex] = useState<string | null>(null);
  // 为 keyData 定义一个类型
  const [keyData, setKeyData] = useState<KeyGroup[]>([]);
  const { t } = useTranslation("");
  // 加载新键位信息
  useEffect(() => {
    if (newKeyInfos?.Keyboard?.list) {
      const updatedKeyData = newKeyInfos.Keyboard.list.map((item) => ({
        ...item,
        show: true, // 初始设置所有项目为折叠状态
      }));
      setKeyData(updatedKeyData);
    }
  }, []);

  // 处理按键点击
  const handleClick = (index: number, sIndex: number) => {
    if (selKeyIndex == 0) {
      toast({
        title: t("leftBtnNoChange"),
        status: "info",
        duration: 3000,
        isClosable: true,
        colorScheme: "blue",
        position: "top",
      });
      return;
    }
    const keyInfo = newKeyInfos.Keyboard.list[index].keycodes[sIndex];
    const newKey = {
      ...mouseKeys[selKeyIndex],
      keyName: keyInfo.name,
      type: keyInfo.type,
      code1: keyInfo.code1,
      code2: keyInfo.code2,
      code3: keyInfo.code3,
    };

    const updatedMouseKeys = mouseKeys.map((key) =>
      key.index === selKeyIndex ? newKey : key
    );

    setMouseKeys(updatedMouseKeys);
    profile.updateMouseKeys(profileIndex, updatedMouseKeys);

    if (connectedMouse) {
      connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
    }
    setNowIndex(`${index}-${sIndex}`);
    toast({
      title: `${t("haveSet")}：${t(keyInfo.name)}`,
      status: "info",
      duration: 3000,
      isClosable: true,
      colorScheme: "blue",
      position: "top",
    });
  };

  // 切换显示/隐藏状态
  const toggleItem = (index: number) => {
    setKeyData((prevData) =>
      prevData.map((item, i) =>
        i === index ? { ...item, show: !item.show } : item
      )
    );
  };

  return (
    <Box className="h-full">
      <Text className="mb-4 text-sm font-semibold text-[#eeeeee]">
        {t("keyAssignTip")}
      </Text>
      <Box
        className="flex flex-col space-y-6 overflow-y-auto "
        sx={{
          height: "calc(100vh - 420px)", // 减去头部和其他固定元素的高度
          minHeight: "300px", // 设置最小高度
        }}
      >
        {keyData.map((item, index) => (
          <Box key={index} className="w-full">
            <Flex
              className="items-center justify-between h-[36px] rounded-lg shadow-sm cursor-pointer"
              onClick={() => toggleItem(index)}
            >
              <Text className="text-lg font-semibold text-white">
                {t(item.name)}
              </Text>
              <IconButton
                icon={item.show ? <ChevronUpIcon /> : <ChevronDownIcon />}
                aria-label="Toggle"
                variant="ghost"
                colorScheme="blue"
              />
            </Flex>
            <Collapse in={item.show}>
              <Box className="space-y-2">
                {item.keycodes.map((key, keyIndex) => (
                  <Box
                    key={keyIndex}
                    className={`p-2 rounded cursor-pointer ${
                      nowIndex === `${index}-${keyIndex}`
                        ? "bg-[rgba(55,65,81,.9)]"
                        : "hover:bg-[rgba(55,65,81,.7)]"
                    }`}
                    draggable={true}
                    onDragStart={(e) => {
                      e.dataTransfer.setData(
                        "keyCode",
                        JSON.stringify({
                          type: key.type,
                          keyName: key.name,
                          code1: key.code1,
                          code2: key.code2,
                          code3: key.code3,
                        })
                      );
                    }}
                    onClick={() => handleClick(index, keyIndex)}
                  >
                    {key.name}
                  </Box>
                ))}
              </Box>
            </Collapse>
          </Box>
        ))}
      </Box>
    </Box>
  );
};

export default KeyboardKey;
